import { Inject, Injectable, Optional } from '@angular/core'
import { AD_RESOURCE_URL } from 'monk-design/config'

@Injectable()
export class AdResourceService {
  constructor(@Optional() @Inject(AD_RESOURCE_URL) private adResourceUrl: string) {}
  getResourcePrefix() {
    return this.adResourceUrl || ''
  }
  getFullPath(resourcePath) {
    return this.getResourcePrefix() + resourcePath
  }

  loadCss(hrefUrl: string) {
    return new Promise<void>((resolve, reject) => {
      // 判断当前css是否已经加载过
      const linkNodes = [].slice.call(document.querySelectorAll('link')).map((item) => item.href)
      if (linkNodes.includes(hrefUrl)) return resolve()
      const link = document.createElement('link')
      link.type = 'text/css'
      link.rel = 'stylesheet'
      link.href = hrefUrl
      document.head.appendChild(link)
      link.onload = () => {
        resolve()
      }
      link.onerror = (err) => {
        reject(err)
      }
    })
  }

  loadIcon() {
    return this.loadCss(this.getFullPath('/assets/monk-design/iconfont/iconfont.css'))
  }
}
